/**
 * Module dependencies.
 */
var path =require('path'),
    join = path.join,
    fs = require('fs');
    express = require('express'),
    ndir = require('ndir'),
    staticDir = join(__dirname, 'webapp'),
    config = require('./config'),
    log = require('./lib/log'),
    errorHandler = require('./lib/ErrorHandler'),
    logger = null,
    accessLogger = null,
    maxAge = 3600000 * 24 * 30;


module.exports = app = express();

fs.mkdir(path.join(staticDir,config.site.upload_dir), 0776,function(err){
    if(err.code !== 'EEXIST'){
        throw err;
    }
});
fs.mkdir('logs', 0776,function(err){
    if(err.code !== 'EEXIST'){
        throw err;
    }
});

logger = log.global;
accessLogger = log.access;

bn = {
    config : config,
    logger : logger
};

//process.on('uncaughtException', function (err) {
//	//console.log(err);
//	logger.error(err,err.message);
//});

//console.log(global.bn);

app.use(function(req, res, next){
    accessLogger.info(req.method,req.ip,req.path,req.header('User-Agent'));
    next();
})
// gzip
app.use(express.compress());
// session support
app.use(express.cookieParser());
app.use(express.session({
    key : 'blog4node.s_id',
    secret: config.site.session_secret
}));
//
app.use(express.methodOverride());
app.use(express.bodyParser());

// csrf
//app.use(express.csrf());
//app.use(function(req,res,next){
//    console.log(req.session._csrf);
//    req.headers['x-csrf-token'] = req.session._csrf;
//    next();
//});
// set static, dynamic helpers
app.locals({
    config: config
});

// old image url: http://host/data/images/xxxx
app.use('/data/', express.static(join(config.site.upload_dir), {
    maxAge: maxAge
}));

app.configure('development', function() {
    app.use(express.static(staticDir));
    app.use(errorHandler({
        showStack: true
    }));
});

app.configure('production', function() {
    app.use(express.static(staticDir, {
        maxAge: maxAge
    }));
    app.use(errorHandler());
});

app.use(function(req ,res ,next){
    var paths = req.path.split("/");
    if(paths[1] === 'services' || paths[1] === 'resources'){
        next();
    }else if(paths[1] === 'admin') {
        res.sendfile(join(staticDir,'admin/index.html'));
    }else {
        res.sendfile(join(staticDir,'index.html'));
    }
});
var services = require('./src/services');

services(app ,config);
logger.info('service loaded complete!');
/*
var dispatcher = require('./src/dispatcher.js');
app.all('/services/:sid*',function(req, res){
    res.set('Content-Type','application/json');
    var sid = req.params['sid'];
	dispatcher(sid, req, res , function(responseModel){
		var result = JSON.stringify(responseModel);
        //console.log(result.length);
		res.send(result);
        //res.set('Content-Length',result.length);
	})
});
*/
var server = app.listen(config.app.port);

logger.info("Express listening on port " + config.app.port + " in " + app.settings.env + " mode");
logger.info("You can debug your app with http://" + config.app.hostname + ':' + config.app.port);